package com.itrip.controller;

import com.alibaba.druid.util.StringUtils;
import com.alibaba.fastjson.JSONObject;
import com.itrip.dto.ResponseDTO;
import com.itrip.maile.RegisterMail;
import com.itrip.pojo.ItripUser;
import com.itrip.service.UserService;
import com.itrip.utils.MD5;
import com.itrip.utils.RegisterMsg;
import com.itrip.vo.user.LoginVO;
import com.itrip.vo.user.RegisterVO;
import io.swagger.annotations.*;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.Date;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

/**
 * 登录、注销、注册
 * 控制器
 */
@Api(tags = "登录，注销，注册")
@ApiResponses({
        @ApiResponse(code = 200,message = "请求正常",response = ResponseDTO.class)
})
@RestController
public class LoginController {
    @Resource
    private UserService userService;

    @Resource
    private RedisTemplate<String,Object> redisTemplate;

    @ApiOperation("用户登录接口")
    @PostMapping(value = "/login", params = {"userCode","userPassword"})
    public ResponseDTO login(LoginVO loginVO){
        loginVO.setUserPassword(MD5.md5(loginVO.getUserPassword()));
        ItripUser user = userService.getUserByLogin(loginVO);
        if (user != null){
            String token = UUID.randomUUID().toString();
            System.out.println(token);
            redisTemplate.opsForValue().set(token,user,30, TimeUnit.MINUTES);

            return new ResponseDTO(100,"登陆成功",token);

        }
        return new ResponseDTO(101,"登陆失败",null);
    }

    @ApiOperation("用户注销接口")
    @ApiImplicitParam(name = "token",value = "token令牌",dataType = "string",paramType = "header",required = true)
    @GetMapping("/view/logout")
    public ResponseDTO logout(HttpServletRequest request){
        String header = request.getHeader("token");
        return new ResponseDTO(100,"注销成功",null);
    }

    @ApiOperation("获取登录用户接口")
    @ApiImplicitParam(name = "token",value = "token令牌",dataType = "string",paramType = "header",required = true)
    @GetMapping("/view/getLoginUser")
    public ResponseDTO getLoginUser(HttpServletRequest request){
        String token = request.getHeader("token");
        Object user = redisTemplate.opsForValue().get(token);
        return new ResponseDTO(100,"获取登录用户成功",user);
    }

    @ApiOperation("获取邮件激活码接口")
    @ApiImplicitParam(name = "email",value = "注销用户的邮箱地址",required = true)
    @GetMapping("/getCodeForMail")
    public ResponseDTO getCodeForMail(@RequestParam String email) throws Exception {
        int code = (int)((Math.random()*9+1)*100000);
        RegisterMail.sendMail(code,email);
        redisTemplate.opsForValue().set(email,code,5,TimeUnit.MINUTES);
        return new ResponseDTO(100,"邮件发送成功",null);
    }

    @ApiOperation("获取短信激活码接口")
    @ApiImplicitParam(name = "phone",value = "注册用户的手机号",required = true)
    @GetMapping("/getCodeForPhone")
    public ResponseDTO getCodeForPhone(@RequestParam String phone) throws Exception {
        int code = (int)((Math.random()*9+1)*100000);
        String send = RegisterMsg.send(phone, code);
        String resultCode = JSONObject.parseObject(send).getString("Code");
        if (!StringUtils.isEmpty(resultCode) && resultCode.equals("OK")){
            redisTemplate.opsForValue().set(phone,code,5,TimeUnit.MINUTES);
            return new ResponseDTO(100,"短信验证码发送成功",null);
        }
        return new ResponseDTO(101,"短信验证码发送失败",null);
    }

    @ApiOperation("获取账号是否已注册")
    @ApiImplicitParam(name = "userCode",value = "注册账号",required = true)
    @GetMapping("/getUserCodeCount")
    public ResponseDTO getUserCodeCount(@RequestParam String userCode) throws Exception {
       int count = userService.getUserCodeCount(userCode);
       String msg = count > 0 ?"账号已存在":"账号不存在";
        return new ResponseDTO(100,msg,null);
    }

    @ApiOperation("用户邮件、手机注册接口")
    @PostMapping(value = "/register",params = {"userCode","userPassword","code"})
    public ResponseDTO register(RegisterVO registerVO){
        Object code = redisTemplate.opsForValue().get(registerVO.getUserCode());
        if (code != null && registerVO.getCode().equals(code.toString())){
            redisTemplate.delete(registerVO.getUserCode());

            ItripUser user = new ItripUser();
            user.setUserCode(registerVO.getUserCode());
            user.setUserPassword(MD5.md5(registerVO.getUserPassword()));
            user.setUserType(0);
            user.setUserName(registerVO.getUserCode());
            user.setCreationDate(new Date());
            user.setActivated(1);
            int count = userService.addUser(user);
            if (count == 1){
                String token = UUID.randomUUID().toString();
                redisTemplate.opsForValue().set(token,user,30,TimeUnit.MINUTES);
                return new ResponseDTO(100,"注册成功",token);
            }

            return new ResponseDTO(101,"注册失败",null);
        }


        return new ResponseDTO(101,"激活码无效",null);


    }
}
